package com.support.mvc.encrypt.convert;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.support.mvc.encrypt.AesApiId;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

/**
 * 用于 JSON 序列化和反序列化， @JSONField(serializeUsing = AesApiIdLongJsonConvert.class, deserializeUsing = AesApiIdLongJsonConvert.class)
 *
 * @author 谢长春 2022-02-06
 */
@Slf4j
public class AesApiIdLongJsonConvert {

//    public static class Serializer implements ObjectSerializer {
//
//        @Override
//        public void write(JSONSerializer serializer, Object value, Object fieldName, Type fieldType, int features) throws IOException {
//            if (Objects.isNull(value)) {
//                return;
//            }
//            if (log.isDebugEnabled()) {
//                log.debug("加密:{}:{}", fieldName, value);
//            }
//            serializer.write(AesApi.encrypt(Objects.toString(value)));
//        }
//    }
//
//    public static class Deserializer implements ObjectDeserializer {
//        @SuppressWarnings({"unchecked"})
//        @Override
//        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
//            final String value = parser.getLexer().stringVal();
//            if (log.isDebugEnabled()) {
//                log.debug("解密:{}:{}", fieldName, value);
//            }
//            return (T) Optional.ofNullable(AesApi.decrypt(value)).map(Long::parseLong).orElse(null);
//        }
//
//        @Override
//        public int getFastMatchToken() {
//            return 0;
//        }
//    }

    /**
     * id 反序列化， 去掉携带的 updateTime
     */
    public static class AesIdDeserializer implements ObjectDeserializer {
        @SuppressWarnings({"unchecked"})
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            final String value = parser.getLexer().stringVal();
            if (log.isDebugEnabled()) {
                log.debug("解密:{}:{}", fieldName, value);
            }
            return (T) AesApiId.decrypt(value).getLongId();
        }

        @Override
        public int getFastMatchToken() {
            return 0;
        }
    }

}
